<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="导出中心"
    width="950"
    draggable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close"
    :z-index="2000"
  >
    <div class="flex py-4">
      <div class="left flex-1 mr-5">
        <div class="flex justify-between">
          <div class="font-medium text-black">字段列表</div>
          <el-button type="primary" text @click="handleRestoreDefault"
            >恢复默认</el-button
          >
        </div>
        <div style="width: 432px">
          <vxe-table ref="table" :data="export_field" :height="804">
            <vxe-column type="checkbox" width="40"></vxe-column>
            <vxe-column type="seq" width="60">
              <template #header>序号</template>
            </vxe-column>
            <vxe-column title="字段" field="field_name" min-width="160"></vxe-column>
            <vxe-column title="排序" width="140">
              <template #default="{ rowIndex }">
                <el-button link type="primary" @click="prevRow(rowIndex)">上移</el-button>
                <el-button link type="primary" @click="nextRow(rowIndex)">下移</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <div class="right flex-1">
        <div class="font-medium text-black">字段列表</div>
        <div class="flex justify-between items-end mb-4">
          <el-button type="primary" @click="handleImport">导出</el-button>
          <div class="flex text-xs text-gray-400 ml-5">
            <svg-icon icon-class="hint_line01"></svg-icon>导出结果在
            <el-link type="primary" :underline="false" @click="navPersonal"
              >个人中心</el-link
            >
            查看
          </div>
        </div>
        <div class="flex items-center mb-2">
          <el-input
            v-model="exportName"
            class="w-full"
            placeholder="请输入名称"
          /><el-button type="primary" plain @click="saveTemplate">保存模版</el-button>
        </div>
        <el-table :data="templates" style="width: 100%" border>
          <el-table-column prop="name" label="名称">
            <template #default="{ row, $index }">
              <el-button type="primary" text @click="handleCellClick(row, $index)">
                {{ row.name }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="opearn" label="操作" width="220">
            <template #default="{ row, $index }">
              <el-button
                v-if="checkIndex === $index"
                link
                type="primary"
                @click="edit(row, $index)"
                >保存</el-button
              >
              <el-button type="primary" link @click="view(row, $index)">查看</el-button>
              <el-button type="primary" link @click="exportRow(row)">导出</el-button>
              <template v-if="row.creator_id == user_id">
                <el-button type="danger" link @click="exportDelete(row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="DerivedCenter" lang="jsx">
import { reactive, toRefs, getCurrentInstance, onMounted } from "vue";
import {
  exportRord,
  exporttpl,
  exportTemplateOne,
  exportTemplateDelete,
  exportTemplateEdit,
} from "@/api/index";
import { ElMessage, ElMessageBox } from "element-plus";
import action from "@/utils/action.js";

const { proxy } = getCurrentInstance();
const emits = defineEmits(["query"]);

const data = reactive({
  form: {
    title: "",
    module: "goods",
    config_id: null,
    condition: null,
  },
  visible: false,
  loading: false,
  export_field: [],
  export_field_init: [],
  multipleSelection: [],
  exportName: "",
  templates: [],
  user_id: "",
  tag_name: "",
  load: false,
});
const {
  visible,
  export_field,
  export_field_init,
  multipleSelection,
  form,
  exportName,
  templates,
  user_id,
  tag_name,
  load,
} = toRefs(data);
const open = async (item) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  visible.value = true;
  form.value.condition = item.condition;
  tag_name.value = item.tag_name;
  getTemplate();
};

const getTemplate = async () => {
  try {
    const res = await exportTemplateOne({
      home_system: 2,
      tag_name: tag_name.value,
    });
    form.value.config_id = res.data.config_id;
    form.value.title = res.data.config_name + "-" + window.userInfo.user.realname;
    const list = res.data.export_field;
    export_field.value = list;
    export_field_init.value = list;
    templates.value = res.data.templates;
    form.value.title = res.data.config_name + window.userInfo.user.realname;
  } catch (e) {
    throw Error(e);
  }
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const prevRow = (index) => {
  const row = export_field.value.splice(index, 1)[0];
  export_field.value.splice(index - 1, 0, row);
  export_field.value = [...export_field.value];
};

const nextRow = (index) => {
  const row = export_field.value.splice(index, 1)[0];
  export_field.value.splice(index + 1, 0, row);
  export_field.value = [...export_field.value];
};

const handleImport = async () => {
  const selection = table?.value.getCheckboxRecords();
  if (selection.length == 0) {
    ElMessage.error("至少勾选一条导出项");
    return;
  }

  const fields = selection.map((i) => i.field_key);
  try {
    const res = await exportRord({
      ...form.value,
      fields,
    });
    // ElMessage.success(res.message);
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: "发起导出成功，请前往系统首页-<strong>导出中心</strong>下载导出文件",
      type: "success",
    });
  } catch (e) {
    throw Error(e);
  }
};

const navPersonal = async () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      path: "/user/profile",
      type: "push",
    },
  });
};

const saveTemplate = async () => {
  if (!exportName.value) {
    ElMessage.error("请输入名称");
    return;
  }
  const selection = table?.value.getCheckboxRecords();
  if (selection.length == 0) {
    ElMessage.error("至少勾选一条导出项");
    return;
  }

  const fields = selection.map((i) => i.field_key);

  try {
    const res = await exporttpl({
      config_id: form.value.config_id,
      name: exportName.value,
      fields,
    });
    ElMessage.success(res.data.message);
    getTemplate();
  } catch (e) {
    throw Error(e);
  }
};

const exportRow = async (row) => {
  const title = row.name + window.userInfo.user.realname;
  try {
    const res = await exportRord({
      tpl_id: row.tpl_id,
      ...form.value,
      title,
      fields: row.fields,
    });
    // ElMessage.success(res.message);
    ElMessage({
      dangerouslyUseHTMLString: true,
      message: "发起导出成功，请前往系统首页-<strong>导出中心</strong>下载导出文件",
      type: "success",
    });
  } catch (e) {
    throw Error(e);
  }
};

const exportDelete = async (row) => {
  try {
    const res = await exportTemplateDelete(row.tpl_id);
    ElMessage.success(res.data.message);
    getTemplate();
  } catch (e) {
    throw Error(e);
  }
};
const table = ref();
const checkIndex = ref("");

// 选中表格一行数据的时候触发
const handleCellClick = async (row, rowIndex) => {
  checkIndex.value = rowIndex;
  // 排序
  const { checkFields, noCheckFields } = export_field.value.reduce(
    (acc, cur) => {
      if (row.fields.includes(cur.field_key)) {
        acc.checkFields.push(cur);
      } else {
        acc.noCheckFields.push(cur);
      }
      return acc;
    },
    { checkFields: [], noCheckFields: [] }
  );

  // 检查并处理不存在的field_key
  const checkedFieldsWithKeys = row.fields.map((d) => {
    const foundField = checkFields.find((c) => d === c.field_key);
    return foundField || { field_key: d }; // 假设cur是默认值或初始状态
  });

  export_field.value = [...checkedFieldsWithKeys, ...noCheckFields];

  // 选中
  await table?.value.clearCheckboxRow();
  const rows = export_field.value.filter((d) => row.fields.includes(d.field_key));
  table?.value.setCheckboxRow(rows, true);
};

onMounted(() => {
  user_id.value = window.userInfo?.user?.user_id;
});

const close = () => {
  exportName.value = "";
  visible.value = false;
};
defineExpose({ open });

// 查看
const view = async (row) => {
  // const names = export_field.value
  //   .filter((d) => row.fields.includes(d.field_key))
  //   .map((d) => d.field_name);

  // 创建一个映射，用于快速查找 field_key 对应的 index
  const fieldKeyIndexMap = new Map(row.fields.map((field, index) => [field, index]));

  // 过滤并排序
  const names = export_field.value
    .filter((d) => row.fields.includes(d.field_key))
    .sort((a, b) => {
      const aIndex = fieldKeyIndexMap.get(a.field_key);
      const bIndex = fieldKeyIndexMap.get(b.field_key);
      return aIndex - bIndex;
    })
    .map((d) => d.field_name);

  // 如果 export_field.value 或 row.fields 是空数组，返回空数组
  if (export_field.value.length === 0 || row.fields.length === 0) {
    names.length = 0;
  }
  await 1;
  ElMessageBox({
    title: row.name,
    showCancelButton: true,
    showConfirmButton: false,
    cancelButtonText: "关闭",
    message: () => (
      <div
        class="flex flex-col gap-2"
        style="max-height: calc(100vh - 160px);overflow-x: hidden;overflow-y: auto"
      >
        {names.map((d) => (
          <div>{d}</div>
        ))}
      </div>
    ),
  }).catch(() => {});
};

// 保存模板
const edit = (row, rowIndex) => {
  const selection = table?.value.getCheckboxRecords();
  if (!selection.length) {
    ElMessage.error("请先选择字段");
    return;
  }
  // loadings['edit' + rowIndex] = true

  exportTemplateEdit(row.tpl_id, {
    name: row.name,
    condition: [],
    fields: selection.map((d) => d.field_key),
  })
    .then((res) => {
      getTemplate();
      ElMessage.success("保存模板成功");
    })
    .finally(() => {
      // loadings['edit' + rowIndex] = false
    });
};

const handleRestoreDefault = () => {
  checkIndex.value = "";
  export_field.value = export_field_init.value;
  if (table.value) {
    table.value.clearCheckboxRow();
  }
};
</script>
